package com.beek.android.jim;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.beek.android.jim.Util;

public class MainActivity extends Activity implements OnSharedPreferenceChangeListener {
  /* Receiver that updates balances in the main app screen */
  BroadcastReceiver updateUIReceiver = new BroadcastReceiver() {
                                       @Override
                                       public void onReceive(Context context, Intent intent) {
                                         updateBalanceText();
                                       }
                                     };
                                     
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    setOnClickSMS(R.id.btnCons, "", "CONSULT");
    setOnClickSMS(R.id.btnTop5, "T", "TOP 5");
    setOnClickSMS(R.id.btnTop10, "T", "TOP 10");
    setOnClickSMS(R.id.btnTop15, "T", "TOP 15");
    setOnClickSMS(R.id.btnSurf, "P", "MEGASURF");
    setOnClickSMS(R.id.btnSms, "P", "SMSALL");
    setOnClickSMS(R.id.btnAll, "P", "ALL");
    setOnClickSMS(R.id.btnInter, "P", "INTER");
    setOnClickSMS(R.id.btnRoam, "P", "ROAM");

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);

    Util.SetAutomatedConsult(this, prefs);
    Util.SetScreenRefreshAtMidnight(this);
  }

  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    if ("automateConsult".equals(key))
      Util.SetAutomatedConsult(this, prefs);
  }

  private void setOnClickSMS(int btnId, final String type, final String message) {
    Button btn = (Button) findViewById(btnId);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        checkSMS(type, message);
      }
    });
  }

  /** Menu opening **/
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
  };

  /** Menu item selection **/
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.settings:
      Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
      startActivity(settingsActivity);
      return true;
    case R.id.help:
      Intent showHelpWebSite = new Intent(Intent.ACTION_VIEW,
          Uri.parse("http://code.google.com/p/jim-mobile-red/wiki/JimMobileRED"));
      startActivity(showHelpWebSite);
      return true;
    default:
      return super.onOptionsItemSelected(item);
    }
  }

  @Override
  public void onPause() {
    super.onPause();
    unregisterReceiver(updateUIReceiver);
  }

  @Override
  public void onResume() {
    super.onResume();
    updateBalanceText();

    registerReceiver(updateUIReceiver, new IntentFilter("update_jimRED_balances_screen"));
  }

  /** update balances overview **/
  private void updateBalanceText() {
    TextView txtBalances = (TextView) findViewById(R.id.balances);

    SharedPreferences balances = getSharedPreferences("balances", 0);
    Map<String, ?> balancesMap = balances.getAll();
    String balancesTxt = "";
    String dateTo = "";
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    boolean notExpired = true;
    int days = 365;
    for (String key : balancesMap.keySet()) {
      if (key.endsWith("_txt")) {
        notExpired = true;
        dateTo = (String) balancesMap.get(key.substring(0, key.length() - 4) + "_dateTo");
        try {
          Date dateToDate = df.parse(dateTo);
          days = (int) ((dateToDate.getTime() - Calendar.getInstance().getTimeInMillis()) / (1000 * 60 * 60 * 24));
          notExpired = (days >= 0); // 0 is OK as it's until expiration date included
        } catch (ParseException e) {
        }
        if (notExpired) {
          balancesTxt += (String) balancesMap.get(key) + "\n";
        }
      }
    }
    if (balancesTxt.length() == 0) {
      txtBalances.setText("no balances known - Hit the Consult button");
    } else {
      txtBalances.setText(balancesTxt);
    }
  }

  /**
   * send an SMS message to another device but ask confirmation from user first
   **/
  private void checkSMS(final String Type, final String message) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String phoneNumber = prefs.getString("phoneNum", "1984");

    if (Type.equals("")) {
      ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo ni = cm.getActiveNetworkInfo();
      if ((ni != null) && (!ni.isRoaming())) { // don't ask confirmation for a Consult when not roaming
        Util.sendSMS(getBaseContext(), Type, message, "");
        return;
      }
    }
    // prepare the alert box
    AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
    alertbox.setMessage("Send " + message + " to " + phoneNumber + " ?");
    alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface arg0, int arg1) {
        Util.sendSMS(getBaseContext(), Type, message, "");
      }
    });
    alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface arg0, int arg1) {
      }
    });
    alertbox.show();
  }

}
